<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" class="my-nav-bar" />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        required
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="登录ing"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入api方法
import { userLogin } from '../../api/login'
// 导入 token工具函数
import { saveToken } from '../../utils/token'
export default {
  name: 'login',

  data () {
    return {
      mobile: '13912348765', // 手机号
      code: '246810', // 验证码
      isLoading: false // 是否正在加载中
    }
  },
  methods: {
    onSubmit (values) {
      // values是一个对象{mobile:'xxx',code:'xxx'}
      // 开启loading
      this.isLoading = true
      userLogin(values)
        .then(res => {
          console.log('res:', res)
          // 保存token
          saveToken(res.data.data)
          setTimeout(() => {
            this.$toast.success('登录成功!')
            this.isLoading = false
            // 判断是否有 redirect参数
            const redirect = this.$route.query.redirect
            if (redirect) {
              return this.$router.push({
                path: redirect
              })
            }
            // 没有 redirect
            this.$router.push({
              path: '/home'
            })
          }, 500)
        })
        .catch(errRes => {
          console.log('errRes:', errRes)
          setTimeout(() => {
            this.$toast.fail('登录失败!')
            this.isLoading = false
          }, 500)
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .my-nav-bar {
    background-color: #3196fa;
    .van-nav-bar__title {
      color: white;
    }
  }
}
</style>
